<template>
  <div ref="jwChat" :style="style" style="position: fixed;">
    <el-button v-show="!showChat" circle icon="el-icon-plus" size="mini" @click="showChat=true"></el-button>
    <JwChat-index
        v-show="showChat"
        v-model="inputMsg"
        :config="config"
        :placeholder="placeholder"
        :scrollType="scrollType"
        :showRightBox="showRightBox"
        :taleList="taleList"
        :toolConfig="tool"
        :winBarConfig="winBarConfig"
        @clickTalk="talkEvent"
        @enter="bindEnter"
    >

      <!--      头部-->
      <template slot="header">
        <div style="float: right;width: 100%;">
          <el-button circle icon="el-icon-minus" size="mini" type="danger" @click="showChat=false"></el-button>
        </div>
      </template>
      <!--      输入框栏-->
      <!--      <template slot="enter">-->
      <!--        <div>自定义输入框</div>-->
      <!--      </template> -->

      <!--      发送按钮栏-->
      <!--      <template slot="enterBtn">-->
      <!--        <div>自定义按钮</div>-->
      <!--      </template>-->

      <!--      <template #downBtn="{unread}">-->
      <!--        <div>-->
      <!--          未读{{unread}}-->
      <!--        </div>-->
      <!--      </template>-->

      <!--      群消息-->
      <!--      <JwChat-rightbox-->
      <!--        class="rightSlot"-->
      <!--        :config="rightConfig"-->
      <!--        @click="rightClick"-->
      <!--      />-->

      <JwChat-talk :Talelist="talk" :config="quickConfig" class="rightSlot" @event="bindTalk"/>
      <!--      聊天工具栏-->
      <!--       <template slot="tools">-->
      <!--        -->
      <!--        <div style="width: 20rem; text-align: right" @click="toolEvent(12)">-->
      <!--          <JwChat-icon type="icon-lishi" title="历史" />-->
      <!--        </div>-->
      <!--      </template>-->

    </JwChat-index>
  </div>

</template>

<script>

import {useDraggable} from '@vueuse/core'
import {format, formatDateTime} from "@/util/DateUtil";
import chatRequest from "@/api/chat";
import UserChatInfoCard from "@/components/jwchat/UserChatInfoCard.vue";
import {errorMessage} from "@/util/Notice";
import {userRequest} from "@/api/user";
import webSocket from "@/api/chat/chat";
import createWs from "@/api/chat/chat";
import ms from "element-ui/src/locale/lang/ms";
import {userApi} from "@/api/user/user";
import chatApi from "@/api/chat/chatApi";

//
// const list = [
//   {
//     "date": "2020/04/25 21:19:07",
//     "text": {"text": "起床不"},
//     "mine": false,
//     "name": "留恋人间不羡仙",
//     "img": "../image/one.jpeg"
//   },
//   {
//     "date": "2020/04/25 21:19:07",
//     "text": {"text": "<audio data-src='https://www.w3school.com.cn/i/horse.mp3'/>"},
//     "mine": false,
//     "name": "只盼流星不盼雨",
//     "img": "../image/two.jpeg"
//   },
//   {
//     "date": "2020/04/25 21:19:07",
//     "text": {"text": "<img data-src='" + img + "'/>"},
//     "mine": false,
//     "name": "只盼流星不盼雨",
//     "img": "../image/two.jpeg"
//   },
//   {
//     "date": "2020/04/25 21:19:07",
//     "text": {"text": "<img data-src='../image/three.jpeg'/>"},
//     "mine": false,
//     "name": "只盼流星不盼雨",
//     "img": "../image/two.jpeg"
//   },
//   {
//     "date": "2020/04/16 21:19:07",
//     "text": {"text": "<video data-src='https://www.w3school.com.cn/i/movie.mp4' controls='controls' />"},
//     "mine": true,
//     "name": "JwChat",
//     "img": "../image/three.jpeg"
//   },
//   {
//     "date": "2021/03/02 13:14:21",
//     "mine": false,
//     "name": "留恋人间不羡仙",
//     "img": "../image/one.jpeg",
//     "text": {
//       system: {
//         title: '在接入人工前，智能助手将为您首次应答。',
//         subtitle: '猜您想问:',
//         content: [
//           {
//             id: `system1`,
//             text: '组件如何使用'
//           },
//           {
//             id: `system2`,
//             text: '组件参数在哪里查看'
//           },
//           {
//             id: 'system',
//             text: '我可不可把组件用在商业'
//           }
//         ]
//       }
//     }
//   },
//   {
//     "date": "2020/04/25 21:19:07",
//     "text": {
//       "text": "<i class='el-icon-document-checked' style='font-size:2rem;'/>",
//       "subLink": {
//         "text": "a.txt",
//         "prop": {
//           underline: false
//         }
//       },
//     },
//     "mine": false,
//     "name": "留恋人间不羡仙",
//     "img": "../image/one.jpeg"
//   },
// ]


export default {
  name: "MiChat",
  components: {UserChatInfoCard},
  data() {
    return {
      style: {},
      wx: {},
      inputMessage: {},
      showChat: true,
      user: {
        id: 1,
        name: "",
        img: "https://img1.baidu.com/it/u=36236965,2799872317&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=375",
        dept: "我是油饼"
      },
      receiver: {},


      scrollType: 'scroll', // scroll  noroll 俩种类型
      placeholder: "请输入内容",
      inputMsg: '',
      taleList: [],
      tool: {
        callback: this.toolEvent
      },
      config: {
        img: "image/cover.png",
        name: "JwChat",
        dept: "最简单、最便捷",
        callback: this.bindCover,
        historyConfig: {
          show: false,
          tip: "加载更多提示框,可以直接使用组件的",
          callback: this.bindLoadHistory,
        },
        quickList: [
          {text: "好的", id: 1},
          {text: "要的", id: 2},
          {text: "嗯", id: 3},

        ],
      },
      rightConfig: {
        listTip: "当前在线",
        notice:
            "【公告】这是一款高度自由的聊天组件，基于AVue、Vue、Element-ui开发。点个赞再走吧 ",
        filterTip: "好友过滤",
        list: [
          {
            name: "JwChat",
            img: "image/three.jpeg",
            id: 1,
          },
          {
            id: 2,
            name: "JwChat",
            img: "image/three.jpeg",
          },
          {
            id: 3,
            name: "JwChat",
            img: "image/three.jpeg",
          },
          {
            id: 4,
            name: "留恋人间不羡仙",
            img: "image/one.jpeg",
          },
          {
            name: "只盼流星不盼雨",
            img: "image/two.jpeg",
          },
        ],
      },
      talk: [
        "快捷回复1",
        "快捷回复2",
        "快捷回复3",
        "快捷回复4",
        "快捷回复5",
        "快捷回复6",
      ],
      quickConfig: {
        nav: ["快捷回复", "超级回复"],
        showAdd: true,
        maxlength: 200,
        showHeader: true,
        showDeleteBtn: true,
      },
      showRightBox: true,
      winBarConfig: {
        active: "0",
        width: "180px",
        listHeight: "60px",
        list: [
          {
            id: "4",
            img: "https://img2.baidu.com/it/u=2007007442,259694230&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=891",
            name: "张三",
            dept: "最简单、最便捷",
            readNum: 1,
          },
          {
            id: "3",
            img: "https://img2.baidu.com/it/u=2007007442,259694230&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=891",
            name: "李四",
            dept: "沙拉黑油",
            readNum: 12,
          },

        ],
        callback: this.handleBindWinBar,
      },
    }
  },
  methods: {
    parseUser(user) {

      return {
        id: user.userId,
        name: user.userNick,
        img: user.avatar,
        dept: "aabbcc",
        readNum: 0
      }
    },
    //根据id获取用户信息，并将其放入左侧栏
    getUserInfo(id) {

      userApi.getUserInfoByUserId(id).then(resp => {

        if (resp.code === 200) {
          let data = resp.data
          this.winBarConfig.list.push(this.parseUser(data))
        } else {
          return {}
        }
      })
    },
    //根据接收者id和pageNum获取 用户和接收者的历史聊天记录
    getHistory(id, pageNum) {
      this.taleList = []
      chatApi.getChatHistoryByReceiverId(id, pageNum).then(resp => {
        if (resp.code === 200) {
          let data = resp.data.list

          for (let talkVo of data) {
            let talk = talkVo.talk
            this.taleList.push({
              "date": talk.createTime,
              "text": {"text": talk.text},
              "mine": talkVo.mine,
              "name": talkVo.mine ? this.user.name : this.receiver.name,
              "img": talkVo.mine ? this.user.img : this.receiver.img
            })
          }
        }

      })
    },
    // 点击左侧用户，设置活动项
    setWinBarActive(item) {
      // 改变聊天框标头
      const {id, dept, name, img} = item

      // 设置活动id
      this.winBarConfig.active = id
      this.config.name = name
      this.config.img = img
      this.config.dept = dept
    },
    // 点击左侧用户触发事件
    handleBindWinBar(item) {

      console.log(item)

      if (item.type === 'winBar') {
        //
        // // 改变聊天框标头
        // const { id, dept, name, img } = item.data

        // 设置active
        this.setWinBarActive(item.data)
        // 设置当前receiver
        this.receiver = item.data

        //   请求历史记录
        this.getHistory(this.winBarConfig.active, 1)
        // 请求成功消除readNum
        item.data.readNum = 0
      }

    },
    /**
     * @description: 点击加载更多的回调函数
     * @param {*}
     * @return {*}
     */

    // 加载历史记录
    async bindLoadHistory() {
      console.log('history')
      const history = new Array(3).fill().map((i, j) => {
        return {
          date: "2020/05/20 23:19:07",
          text: {text: j + new Date()},
          mine: false,
          name: "JwChat",
          img: "image/three.jpeg",
        };
      });
      let list = history.concat(this.taleList);
      this.taleList = list;
      console.log("加载历史", list, history);
      //  加载完成后通知组件关闭加载动画
      this.config.historyConfig.tip = "加载完成";
      this.$nextTick(() => {
        this.$refs.jwChat.finishPullDown();
      });
    },
    // 将信息放入聊天框数组
    pushMessage() {
      const text = this.inputMessage
      if (!text) return;


      let msg
      if (text.showtext) {
        msg = text.showtext
      } else {
        msg = text
      }
      const msgObj = {
        "date": formatDateTime(new Date()),
        "text": {"text": msg},
        "mine": true,
        "name": this.user.name,
        "img": this.user.img
      }
      this.taleList.push(msgObj)
    },
    // 向ws发送消息
    sendWsMessage(text) {
      // 不能自己发给自己
      if (this.user.id === this.receiver.id) {
        this.$message.error("出现未知错误!")
        return
      }
      let talkObj = {
        text: text,
        // 接受者为左侧用户栏当前选中用户的id
        receiver: this.winBarConfig.active,
        receiverType: 1
      }
      this.ws.send(JSON.stringify(talkObj))
      // 把自己的消息加入数组
      this.pushMessage()

    },
    // 发送消息,手动输入消息为String,快捷消息为obj
    // { id: 8
    // showtext: "总在不经意<b>的</b>年生。回首彼岸。纵然发现光景绵长。"
    // text: "总在不经意的年生。回首彼岸。纵然发现光景绵长。"}
    bindEnter(e) {

      this.inputMessage = e
      if (e.showtext) {
        this.sendWsMessage(e.showtext)
      } else {
        this.sendWsMessage(e)
      }

    },

    // 点击工具栏触发事件
    toolEvent(type, obj) {
      console.log('tools', type, obj)
    },
    // 点击聊天框头像
    talkEvent(play) {
      console.log(play)


    },
    rightClick(type) {
      console.log("rigth", type);
    },
    bindTalk(play) {
      console.log("talk", play);
      const {key, value} = play;
      if (key === "navIndex")
        this.talk = [1, 1, 1, 1, 1, 1, 1, 1].reduce((p) => {
          p.push("随机修改颜色 #" + Math.random().toString(16).substr(-6));
          return p;
        }, []);
      if (key === "select") {
        this.inputMsg = value;
        this.bindEnter();
      }
      if (key === "delIndex") {
        this.talk.splice(value, 1);
      }
    },
    // 处理服务器发来的消息
    handleServerMessage(resp) {

      if (resp.code === 200) {
        let data = resp.data
        // 查找左侧列表是否有发送者

        let item = this.winBarConfig.list.find((item) => {
          return item.id === data.sender
        })
        if (item) {
          // 左侧存在用户

          // 是当前活动用户,直接添加消息
          if (this.winBarConfig.active === data.sender) {
            this.taleList.push({
              "date": data.createTime,
              "text": {"text": data.text},
              "mine": false,
              "name": data.sender,
              "img": ""
            })

          } else {
            // 不是当前活动，添加未读数量
            item.readNum++
          }

        } else {
          // 左侧不存在用户
          // 请求用户信息
          let user = {
            id: data.sender,
            name: "测试",
            dept: "测试介绍",
            img: "",
            readNum: 1
          }
          // 添加至左侧
          this.winBarConfig.list.push(user)
        }


      } else {
        this.$message.error(resp.msg)
      }
    },
    // 初始化ws（获取ws）
    initWebSocket() {
      this.ws = createWs()
      this.ws.onmessage = (e) => {

        let result = JSON.parse(e.data);
        this.handleServerMessage(result)

      }
      // 发送错误，重连三次
      this.ws.onerror = (error) => {
        console.log(error)
        for (let i = 0; i < 3; i++) {
          this.ws = createWs()
          if (this.ws) {
            break;
          }
        }
      }

    },

    // 初始化左侧用户栏
    initWinBarList() {
      // 添加需要聊天的好友列表
      this.getUserInfo(1)
      this.getUserInfo(2)
      // 默认设置聊天框信息为好友列表第一个
      if (this.winBarConfig.list.length > 0) {
        let item = this.winBarConfig.list[0]
        this.setWinBarActive(item)
      }

    },

    // 初始化用户本人
    initUser() {
      let user = this.$store.state.userOption.user;
      this.user = {
        id: user.userId,
        name: user.userNick,
        img: user.avatar,
        dept: "暂时没有"
      }
    },
    initMoveAble() {
      let {x, y, style} = useDraggable(this.$refs.jwChat, {
        initialValue: {x: 400, y: 40},
      })
      this.style = style
    }
  },
  mounted() {
    this.initMoveAble()
    this.initWebSocket()
    this.initWinBarList()
    this.initUser()
  }
}
</script>
<style lang="less" scoped>

</style>
